<?php
/**
 * Created by PhpStorm.
 * User: ye
 * Date: 2017/11/19
 * Time: 下午9:49
 */

namespace App\Http\Controllers;


use App\Book;
use App\BookUser;
use App\Common\BookSearch;
use App\Third\Ifff;
use App\User;
use GuzzleHttp\Client;
use Illuminate\Http\Request;

class BookController extends CheckController {
    // 增加翻页
    public function index(Request $request) {
        $perpage = $request->input('perpage', 10);
        $next_cursor = $request->input('next_cursor', 1);

        $booksSearch = new BookSearch($this->userinfo);
        $books = $booksSearch->search($request->all());

        return $this->output(
            200,
            '获取所有图书', [
                'books' => $books,
                'has_more' => count($books) == $perpage,
                'next_cursor' => $next_cursor + 1
            ]
        );
    }

    public function store(Request $request) {
        // 先判断是13位还是10位 纯数字
        $isbn = $request->input('isbn', null);
        $scanType = $request->input('scanType', null);

        if ($isbn == null || !is_numeric($isbn) || !preg_match("/^\d{10}|\d{13}$/", $isbn)|| $scanType == null) {
            return $this->output(400, '提供数据有误');
        }

        $isIsbn = 0;

        if ($scanType == 'EAN_13') {
            $isIsbn = 13;
        } else if ($scanType == 'EAN_10') {
            $isIsbn = 10;
        }

        if ($isIsbn == 0) {
            return $this->output(401, '提供数据有误');
        }

        // todo 判断是否已经发布过同类图书了，第一版是相同的书只有一本
        if ($isIsbn == 13) {
            $has_books = $this->userinfo->books()->where('isbn', $isbn)->first();
        } else {
            $has_books = $this->userinfo->books()->where('isbn10', $isbn)->first();
        }

        if ($has_books) {
            return $this->output(201, '您已存在该本书', ['book' => $has_books]);
        }

        $book_from_db = $isIsbn == 13 ? Book::where('isbn', $isbn)->first() : Book::where('isbn10', $isbn)->first();

        if ($book_from_db) {
            $user_book = new BookUser;
            $user_book->user_id = $this->userinfo->id;
            $user_book->book_id = $book_from_db->id;

            $user_book->save();

            if ($user_book) {
                $ifff = new Ifff();
                $ifff->send2ifff($this->userinfo->username, "上传了一本书「$book_from_db->title」", $book_from_db->pic);
                return $this->output(200, '输入成功', ['book' => $book_from_db]);
            } else {
                return $this->output(402, '存入失败');
            }
        }

        $client = new Client();

        $data = [
            'query' => [
                'isbn' => $isbn
            ],
            'headers' => [
                'Authorization' => "APPCODE ".config('aliyunapi.appcode_isnb')
            ]
        ];
        $response = $client->get(config('aliyunapi.isbn_query_url'), $data);

        $callback = json_decode($response->getBody()->getContents());

        if ($callback->status == 0) {
            $book = new Book();
            $book_callback =$book->aliyun2Book($callback->result);

            if ($book) {
                $user_book = new BookUser;
                $user_book->user_id = $this->userinfo->id;
                $user_book->book_id = $book->id;

                $user_book->save();

                if ($user_book) {
                    $ifff = new Ifff();
                    $ifff->send2ifff($this->userinfo->username, "上传了一本书「$book->title」", $book->pic);

                    return $this->output(200, '输入成功', ['book' => $book_callback]);
                } else {
                    return $this->output(403, '存入失败');
                }
            }
        } else {
            return $this->output(404, '请求的图书不存在');
        }

        return $this->output(405, '请求的图书不存在');
    }

    /**
     * @param $id 传入的是 user_book_id，而不是 book_id
     * @return json
     */
    public function show($id) {
        $book = BookUser::with('book', 'qius.user')->find($id);

        if ($this->userinfo->id == $book->user_id) {
            $status = $book->has_zenged == 0 ? 0 : 1;
        } else {
            $qiu = $this->userinfo->qius()->where('book_user_id', $id)->first();
            $status = $qiu ? 2 : 3;
        }
        if ($book) {
            return $this->output(200, '查找成功', [
                    'book' => $book,
                    'id' => $id,
                    'status' => $status,
                    'status_message' => config('xcx.status_message')[$status]
                ]
            );
        } else {
            return $this->output(200, '查找失败', ['id' => $id]);
        }
    }
}